﻿using System.Collections.Generic;
using System.Data.EntityClient;
using ASPItalia.ModelVirtualCasting.EntityFramework.Wrappers;
using System.Data.Entity;
using System.Linq;
using System;
using System.Linq.Expressions;

namespace ASPItalia.ModelVirtualCasting.EntityFramework
{
	public class BaseRepository<T> where T : class
	{
		public BaseRepository(IContextContainer container)
		{
			Context = container.Current;
			CurrentSet = CreateSet();
			CreateQueryInternal();
			Commands = new List<EntityCommand>();
		}

		internal BaseRepository(IDbSet<T> set)
		{
			CurrentSet = set;
			CreateQueryInternal();
		}

		public IDbSet<T> CurrentSet { get; set; }
		protected IQueryable<T> CurrentQueryableSet { get; private set; }
		protected IContextWrapper Context { get; set; }
		protected List<EntityCommand> Commands { get; set; }
		protected bool CreateNewContextAfterSaveChanges { get; set; }

		protected void SaveChanges()
		{
			Context.SaveChanges(Commands, CreateNewContextAfterSaveChanges);
		}

		internal IDbSet<T> CreateSet()
		{
			return Context.CreateDbSet<T>();
		}

		protected void SetLazyLoading(bool enabled)
		{
			Context.EnableLazyLoading = enabled;
		}

		public void DoNotTrackInternal()
		{
			CurrentQueryableSet = CurrentQueryableSet.AsNoTracking();
		}

		public void CreateQueryInternal()
		{
			CurrentQueryableSet = CreateSet().AsQueryable();
		}

		public void IncludeInternal<TProperty>(Expression<Func<T, TProperty>> path)
		{
			CurrentQueryableSet = CurrentQueryableSet.Include(path);
		}

		public void IncludeInternal(string path)
		{
			CurrentQueryableSet = CurrentQueryableSet.Include(path);
		}
	}
}